package com.framework.component.extension.register;

import com.framework.component.extension.anno.Extension;
import com.framework.component.extension.anno.ExtensionPoint;
import com.framework.component.extension.context.BizScenario;
import com.framework.component.extension.exception.ExtensionException;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

@Component
public class ExtensionRegister {

    private static final String EXTENSION_DEFINE_DUPLICATE = "extension_define_duplicate";

    private final ExtensionRepository repository;

    public ExtensionRegister(ExtensionRepository repository) {
        this.repository = repository;
    }

    public void register(ExtensionPoint extensionPoint) {
        Extension annotation = AnnotationUtils.findAnnotation(extensionPoint.getClass(), Extension.class);
        if (annotation == null) {
            return;
        }

        BizScenario bizScenario = BizScenario.valueOf(annotation.bizId(), annotation.useCase(), annotation.scenario());
        ExtensionPoint ext = repository.getRepositoryRepo().put(calculateExtensionPoint(extensionPoint.getClass(), bizScenario.getUniqueKey()), extensionPoint);
        if (ext != null) {
            throw new ExtensionException(EXTENSION_DEFINE_DUPLICATE);
        }
    }

    private String calculateExtensionPoint(Class<? extends ExtensionPoint> targetClz, String bizUniqueKey) {
        return bizUniqueKey + BizScenario.SPLIT_CHAR + targetClz.getName();
    }

}
